package com.tajiang.business.common.receiver;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.igexin.sdk.PushConsts;
import com.tajiang.business.R;
import com.tajiang.business.common.application.TJApp;
import com.tajiang.business.common.dialog.DialogWithTwoButton;
import com.tajiang.business.common.utils.AppUtils;
import com.tajiang.business.common.utils.AudioPlayerUtils;
import com.tajiang.business.common.utils.CommandTools;
import com.tajiang.business.common.utils.LogUtils;
import com.tajiang.business.common.utils.RequestUtil;
import com.tajiang.business.common.utils.SharedPreferencesUtils;
import com.tajiang.business.common.utils.ToastUtils;
import com.tajiang.business.common.utils.UserUtils;
import com.tajiang.business.login.activity.LoginActivity;
import com.tajiang.business.model.Notify;
import com.tajiang.business.model.User;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;

public class PushTaJiangReceiver extends BroadcastReceiver {

    public static final int NOTIFICATION_ID = 2;

    public static final String NEW_ORDER_MESSAGE = "new_order_message";
    public static final String NEW_MESSAGE = "new_message";

//    给商家推送： takeorder 商家接单 confirm   确认送达
//    所有端推送： offline 下线

    public static final String PUSH_MSG_OFFLINE = "offline";//下线
    public static final String PUSH_MSG_CONFIRM = "confirm";//确认送达
    public static final String PUSH_MSG_TAKERORDER = "takeorder";//商家接单

    private ReceiveNewMessager messager;

    public interface ReceiveNewMessager{
        public void showMessage(String message);
    }

    public void setReceiveNewMessager(ReceiveNewMessager messager) {
        this.messager = messager;
    }
    /**
     * 应用未启动, 个推 service已经被唤醒,保存在该时间段内离线消息(此时 GetuiSdkDemoActivity.tLogView == null)
     */
    public static StringBuilder payloadData = new StringBuilder();

    @Override
    public void onReceive(Context context, Intent intent) {

        Bundle bundle = intent.getExtras();

        LogUtils.e("GetuiSdkDemo", "onReceive() action=" + bundle.getInt("action"));

//        AudioPlayerUtils.playOrderNotifyAudio();  //弹出语言通知

        switch (bundle.getInt(PushConsts.CMD_ACTION)) {

            case PushConsts.GET_MSG_DATA:

                byte[] payload = bundle.getByteArray("payload");

                if (payload != null) {

                    String strData = new String(payload);

                    JSONObject pushObj = null;
                    try {
                        pushObj = new JSONObject(strData);

                        String category = pushObj.optString("category");
                        String title = pushObj.optString("title");
                        String content = pushObj.optString("content");
                        int showType = pushObj.optInt("showType");

                        LogUtils.e("GetuiSdkDemo", pushObj.toString());

                        //离线消息，重新登录
                        if(category.equals(PUSH_MSG_OFFLINE)){

                            RequestUtil.code = RequestUtil.ERROR_USER_INFO;
                            final Activity mActivity = CommandTools.getGlobalActivity();
                            DialogWithTwoButton.showDialog(mActivity, "取消", "重新登录", content, new DialogWithTwoButton.DialogCallback() {

                                @Override
                                public void callback(int position) {

                                    if(position == 1){

                                        Intent intent = new Intent(mActivity, LoginActivity.class);
                                        mActivity.startActivity(intent);
                                    }
                                }
                            });
                        }
                        //商家接单
                        else if(category.equals(PUSH_MSG_TAKERORDER)){

                            if (TJApp.new_order_noice) {
                                AudioPlayerUtils.playOrderNotifyAudio();  //弹出语言通知
                            }
                        }else{
                            ToastUtils.showShort(content);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                break;

            case PushConsts.GET_CLIENTID:
                // 获取ClientID(CID)
                // 第三方应用需要将CID上传到第三方服务器，并且将当前用户帐号和CID进行关联，以便日后通过用户帐号查找CID进行消息推送
                String cid = bundle.getString("clientid");
                SharedPreferencesUtils.put(SharedPreferencesUtils.CLIENT_ID, cid);
                LogUtils.d(cid);
                break;
            case PushConsts.GET_SDKONLINESTATE:
                boolean online = bundle.getBoolean("onlineState");
                Log.d("GetuiSdkDemo", "online = " + online);
                break;

            case PushConsts.SET_TAG_RESULT:
                String sn = bundle.getString("sn");
                String code = bundle.getString("code");

                break;
            case PushConsts.THIRDPART_FEEDBACK:

                break;

            default:
                break;
        }
    }

    private void NotifyUser(Context context, byte[] payload) {
        if (payload != null) {
            String data = new String(payload);
            Notify notify = parseJson2Notify(data);
            boolean isAutoPrint = (Boolean) SharedPreferencesUtils.get(SharedPreferencesUtils.AUTO_PRINT, false);
            boolean isAudioOpen = (Boolean) SharedPreferencesUtils.get(SharedPreferencesUtils.AUDIO_ATTENTION, false);

            //自动打印订单
//            receiveOrder2Print(context, notify, isAutoPrint);   //接收数据
            Notification2User(context, notify);  //弹出通知
            if (isAudioOpen) {
                AudioPlayerUtils.playOrderNotifyAudio();  //弹出语言通知
            }

            LogUtils.e("Json ------>" + data + "<------Json" );
//            Intent intent = new Intent(NEW_ORDER_MESSAGE);
//            intent.putExtra(NEW_MESSAGE,data);
//            context.sendBroadcast(intent);
        }
    }

    private void Notification2User(Context context, Notify notify) {

        String newMsg = "新消息";
        String msg = "";

        switch (notify.getType()) {
            case Notify.TYPE_ORDER:
                msg = "您有新的订单,点击查看";
                break;
        }
        Intent intent;
        //判断APP是否存活
        if (AppUtils.isAppAlive(context)) {
            if (SharedPreferencesUtils.contains(SharedPreferencesUtils.USER_LOGIN_INFOR)) {
                intent = new Intent(context, com.tajiang.business.common.activity.HomeActivity.class);
            } else {
                intent = new Intent(context, com.tajiang.business.login.activity.LoginActivity.class);
            }
        } else {
            PackageManager manager = context.getPackageManager();
            intent = manager.getLaunchIntentForPackage(TJApp.MY_PKG_NAME);
        }

        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
                context).setContentTitle("通知")
                .setContentText(msg)
                .setTicker("新消息")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pendingIntent);//执行intent

        notificationBuilder.setAutoCancel(true);//自己维护通知的消失

        Notification notification = notificationBuilder.build();

        notification.flags |= Notification.FLAG_AUTO_CANCEL;
//        notification.sound = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.audio_new_order);
        notification.defaults = Notification.DEFAULT_SOUND;
        notification.vibrate = new long[]{500L, 200L, 200L, 500L};
        NotificationManager notificationManager = (NotificationManager) TJApp.getInstance()
                .getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(NOTIFICATION_ID, notification);
    }

    /**
     * 接收来自推送的数据
     */
    private void receiveOrder2Print(Context context, Notify notify, boolean isAutoPrint) {
        User user = UserUtils.getUser();
        //判断APP是否存活
        if (AppUtils.isAppAlive(context) && notify != null && user != null) {
            switch (notify.getType()) {
                case Notify.TYPE_ORDER:
                    //关闭自动打印，不打印不弹出新消息
                    if (isAutoPrint) {

                    }
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 解析来自推送的订单
     */
    private Notify parseJson2Notify(String json) {

        Notify notify = null;
        Gson gson = new Gson();
        try {
            Type type = new TypeToken<Notify>() {}.getType();
            notify = gson.fromJson(json, type);
        } catch (Exception e) {
            LogUtils.e(e.getMessage());
        }
        return notify;
    }


}


